from pydantic import BaseModel, EmailStr, Field, validator
from typing import Optional, List, Dict, Any
from datetime import datetime
from enum import Enum

# 基础模型
class BaseUser(BaseModel):
    username: str = Field(..., min_length=3, max_length=50)
    email: Optional[EmailStr] = None
    phone: Optional[str] = Field(None, min_length=11, max_length=11)
    remark: Optional[str] = Field(None, max_length=500)

# 创建用户模型
class UserCreate(BaseUser):
    password: str = Field(..., min_length=8, max_length=30)
    role_ids: Optional[List[int]] = Field(default_factory=list)

    @validator('password')
    def password_strength(cls, v):
        if not any(c.isupper() for c in v):
            raise ValueError('密码必须包含至少一个大写字母')
        if not any(c.islower() for c in v):
            raise ValueError('密码必须包含至少一个小写字母')
        if not any(c.isdigit() for c in v):
            raise ValueError('密码必须包含至少一个数字')
        special_chars = '!@#$%^&*()_+-=[]{}|;:,.<>?`~'
        if not any(c in special_chars for c in v):
            raise ValueError('密码必须包含至少一个特殊字符')
        return v

# 更新用户模型
class UserUpdate(BaseModel):
    username: Optional[str] = Field(None, min_length=3, max_length=50)
    email: Optional[EmailStr] = None
    phone: Optional[str] = Field(None, min_length=11, max_length=11)
    password: Optional[str] = Field(None, min_length=8, max_length=30)
    status: Optional[int] = Field(None, ge=0, le=1)
    role_ids: Optional[List[int]] = None
    remark: Optional[str] = Field(None, max_length=500)

    @validator('password')
    def password_strength(cls, v):
        if v is None:
            return v
        if not any(c.isupper() for c in v):
            raise ValueError('密码必须包含至少一个大写字母')
        if not any(c.islower() for c in v):
            raise ValueError('密码必须包含至少一个小写字母')
        if not any(c.isdigit() for c in v):
            raise ValueError('密码必须包含至少一个数字')
        special_chars = '!@#$%^&*()_+-=[]{}|;:,.<>?`~'
        if not any(c in special_chars for c in v):
            raise ValueError('密码必须包含至少一个特殊字符')
        return v

# 用户查询模型
class UserQuery(BaseModel):
    username: Optional[str] = None
    email: Optional[EmailStr] = None
    status: Optional[int] = Field(None, ge=0, le=1)
    role_id: Optional[int] = None
    page: int = Field(1, ge=1)
    page_size: int = Field(10, ge=1, le=100)

# 用户响应模型
class UserRead(BaseModel):
    id: int
    username: str
    email: Optional[str]
    phone: Optional[str]
    status: int
    avatar: Optional[str]
    remark: Optional[str]
    last_login_at: Optional[datetime]
    created_at: datetime
    updated_at: datetime

    class Config:
        orm_mode = True

# 用户角色响应模型
class RoleRead(BaseModel):
    id: int
    name: str
    description: Optional[str]

    class Config:
        orm_mode = True

# 用户详情响应模型（包含角色信息）
class UserDetailRead(UserRead):
    roles: List[RoleRead] = []

# 登录请求模型
class LoginRequest(BaseModel):
    username: str
    password: str

# 令牌响应模型
class Token(BaseModel):
    access_token: str
    refresh_token: str
    token_type: str = 'bearer'
    expires_in: int

# 令牌负载模型
class TokenPayload(BaseModel):
    user_id: int

# 分页响应模型
class PageResponse(BaseModel):
    total: int
    page: int
    page_size: int
    total_pages: int

# 用户列表分页响应模型
class UserPageResponse(PageResponse):
    data: List[UserRead] = []

# 角色创建模型
class RoleCreate(BaseModel):
    name: str = Field(..., min_length=2, max_length=50)
    description: Optional[str] = Field(None, max_length=500)
    permission_ids: List[int] = Field(default_factory=list)

# 角色更新模型
class RoleUpdate(BaseModel):
    name: Optional[str] = Field(None, min_length=2, max_length=50)
    description: Optional[str] = Field(None, max_length=500)
    status: Optional[int] = Field(None, ge=0, le=1)
    permission_ids: Optional[List[int]] = None

# 权限响应模型
class PermissionRead(BaseModel):
    id: int
    name: str
    code: str
    module: str
    description: Optional[str]

    class Config:
        orm_mode = True

# 角色详情响应模型（包含权限信息）
class RoleDetailRead(RoleRead):
    permissions: List[PermissionRead] = []

# 角色列表分页响应模型
class RolePageResponse(PageResponse):
    data: List[RoleRead] = []

# 权限列表响应模型
class PermissionListResponse(BaseModel):
    data: List[PermissionRead] = []
    total: int

# 批量操作模型
class BatchOperation(BaseModel):
    ids: List[int] = Field(..., min_items=1)